using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Rebus.Config;
using Rebus.Kafka;
using Rebus.Retry.Simple;
using Rebus.Routing.TypeBased;
using Rebus.ServiceProvider;
using Serilog;
using Stee.CAP8.Saga.Sample.Message.Events;
using Stee.CAP8.Saga.Sample.Stock.Handlers;

namespace Stee.CAP8.Saga.Sample.Stock
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddRebus(configure => configure
           //.Logging(l => l.Serilog(Log.Logger))
           .Transport(t => t.UseKafka(brokerList: "127.0.0.1:9092",
                                      inputQueueName: "scaleout.producer"))

            .Routing(x => x.TypeBased().Map<OrderStockAvailableEvent>("scaleout.producer"))
            //.Routing(x => x.TypeBased())
            .Options(o =>
            {
                o.SimpleRetryStrategy(maxDeliveryAttempts: 10, secondLevelRetriesEnabled: true);
            })
           .Sagas(sa => sa.StoreInSqlServer(Configuration.GetConnectionString("Database"),
                                            Configuration.GetValue<string>("SagaDataTableName"),
                                            Configuration.GetValue<string>("SagaIndexTableName"),
                                            true))
           .Timeouts(to => to.StoreInSqlServer(
               Configuration.GetConnectionString("Database"),
               Configuration.GetValue<string>("TimeoutsTableName"),
               true))
            );
            
            services.AddRebusHandler<StockHandler>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.ApplicationServices.UseRebus(async bus =>
            {
                //tell rebus which events to watch out for
                await bus.Subscribe<StockReserveEvent>();
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
